package com.wander.juc.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;

public class ExchangerExample {

    public static void main(String[] args) {

        Exchanger<List<String>> exchanger = new Exchanger<>();

        //生产者线程
        new Thread(()->{
            List<String> list = new ArrayList<>();
            try {
                while (true){
                    list.add("Data-" + System.currentTimeMillis());
                    Thread.sleep(500);
                    //缓冲区满后交换给消费者
                    if (list.size() >= 5) {
                        list = exchanger.exchange(list);
                        System.out.println("生产者已发送数据");
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        new Thread(()->{
            List<String> list = new ArrayList<>();
            try {
                while (true){
                    //从生产者获取数据
                    list = exchanger.exchange(list);
                    System.out.println("消费者收到数据： " + list);
                    list.clear();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }

}
